package probe.logic;

import java.util.ArrayList;


public class Search {
	
	private int _displayType;
	private String _displayDetails;
	private ArrayList<Task> _list, _displayList;
	
	private static final int BY_STATUS = 1;
	private static final int BY_DATE = 2;
	private static final int BY_TASKNAME = 3;
	private static final int ALL = 4;
	
	private static final String STATUS_DONE = "DONE";
	private static final String STATUS_UNFINISHED = "UNFINISHED";
	private static final String DISPLAY_ALL = "ALL";
	
	public Search() {
		_displayList = new ArrayList<Task>();
	}
	
	public void verifyDisplayType() {
		if(_displayDetails.equals(DISPLAY_ALL)) {
			_displayType = ALL;
		}
		if(_displayDetails.equals(STATUS_DONE) || _displayDetails.equals(STATUS_UNFINISHED)) {
			_displayType = BY_STATUS;
		} else {
			try {
				Date date = new Date(_displayDetails);
				if(date.isValidDate())
					_displayType = BY_DATE;
				else
					_displayType = BY_TASKNAME;
			} catch (NumberFormatException e) 
			{		
				_displayType = BY_TASKNAME;
			}
		}
	}
	
	public void doSearch() {
		if(_displayType == ALL) {
			searchAll();
		}
		if(_displayType == BY_STATUS) {
			searchByStatus();
		}
		if(_displayType == BY_DATE) {
			searchByDate();
		}
		if(_displayType == BY_TASKNAME) {
			searchByTaskName();
		}
	}
	
	private void searchAll() {
		_displayList = _list;
	}

	private void searchByStatus() {
		
		if(_displayDetails.equals("UNFINISHED")) {
			for(int i = 0; i < _list.size(); i++) {
				Task task = _list.get(i);
				if(task.taskStatus == Task.TaskStatus.UNFINISHED)
					_displayList.add(task);
			}
		} else {
			for(int i = 0; i < _list.size(); i++) {
				Task task = _list.get(i);
				if(task.taskStatus == Task.TaskStatus.DONE)
					_displayList.add(task);
			}
		}
	}

	private void searchByDate() {
		
		Date date = new Date(_displayDetails);
		for(int i = 0; i < _list.size(); i++) {
			Task task = _list.get(i);
			if(task.taskType == Task.TaskType.DEADLINE_TASK) {
				if(task.deadline.isSameDate(date))
					_displayList.add(task);
			}
			if(task.taskType == Task.TaskType.STET_TASK) {
				if(task.startingDate.isSameDate(date))
					_displayList.add(task);
				else if(task.endingDate.isSameDate(date))
					_displayList.add(task);
			}
		}
		
	}
	
	private void searchByTaskName() {
		
		for(int i = 0; i < _list.size(); i++) {
			Task task = _list.get(i);
			if(task.taskName.equalsIgnoreCase(_displayDetails))
				_displayList.add(task);
		}
	}
	
	public ArrayList<Task> process(ArrayList<Task> list, String command) {
		
		_displayList = new ArrayList<Task>();
		_list = list;
		_displayDetails = command;
		verifyDisplayType();
		doSearch();
		
		return _displayList;
		
	}
}
